package com.ky.server.main;

import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.omg.CORBA.Request;

import com.ky.common.dto.Dto;
import com.ky.common.util.KeyConstants;
import com.ky.server.service.DownloadService;
import com.ky.server.service.FileListService;
import com.ky.server.service.LoginService;
import com.ky.server.service.RegisterService;
import com.ky.server.service.service;

public class KyServerTaskRunnable implements Runnable{

	private Socket ClientSocket;
	
	public KyServerTaskRunnable(Socket clientSocket) {
		super();
		ClientSocket = clientSocket;
	}

	@Override
	public void run() {
		/*
		 * 服务器端等待受理客户端请求
		 * 请求类型，传的数据
		 */
		ObjectInputStream ois=null;
		ObjectOutputStream oos=null;
		try {
			ois=new ObjectInputStream(ClientSocket.getInputStream());
			oos=new ObjectOutputStream(ClientSocket.getOutputStream());
			//服务器读取客户端发来的请求
			Dto<?> requestDto = (Dto<?>) ois.readObject();
			//获取客户端发来的请求中的关键字key
			String key = requestDto.getKey();
			service service=null;
			switch (key) {
			case KeyConstants.REGISTER:
				System.out.println("客户端"+ClientSocket.getInetAddress().getHostAddress()+"："+ClientSocket.getPort()+"发起了请求--->"+KeyConstants.REGISTER);
				service=new RegisterService();
				break;
			case KeyConstants.LOGIN:
				System.out.println("客户端"+ClientSocket.getInetAddress().getHostAddress()+"："+ClientSocket.getPort()+"发起了请求--->"+KeyConstants.LOGIN);
				service=new LoginService();
				break;
			case KeyConstants.FILELIST:
				System.out.println("客户端"+ClientSocket.getInetAddress().getHostAddress()+"："+ClientSocket.getPort()+"发起了请求--->"+KeyConstants.FILELIST);
				service=new FileListService();
				break;
			case KeyConstants.DOWMLOAD:
				System.out.println("客户端"+ClientSocket.getInetAddress().getHostAddress()+"："+ClientSocket.getPort()+"发起了请求--->"+KeyConstants.DOWMLOAD);
				service=new DownloadService();
				break;
			}
			//在服务器端进行业务处理，并返回dto对象
			Dto responseDto=service.service(requestDto.getKey());
			//将服务器端的响应写给客户端
			oos.writeObject(responseDto);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			
			try {
					if(oos!=null) {
						oos.close();
					}
					if(ois!=null) {
						ois.close();
					}
					if(ClientSocket!=null) {
						ClientSocket.close();
					}
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
